package com.ebelter.btcomlib.utils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

/**
 * sha256文件检验码
 * @author fenghui
 *
 */
public class Sha256Utils {
	public static byte[] createChecksum(String filename) throws Exception {
		InputStream fis = new FileInputStream(filename);

		byte[] buffer = new byte[1024];
		MessageDigest complete = MessageDigest.getInstance("SHA-256"); // 如果想使用SHA-1或SHA-256，则传入SHA-1,SHA-256
		int numRead;

		do {
			numRead = fis.read(buffer); // 从文件读到buffer，最多装满buffer
			if (numRead > 0) {
				complete.update(buffer, 0, numRead); // 用读到的字节进行MD5的计算，第二个参数是偏移量
			}
		} while (numRead != -1);

		fis.close();
		return complete.digest();
	}

	public static String getMD5Checksum(String filename) {
		try {
			byte[] b = createChecksum(filename);
			String result = "";

			for (byte aB : b) {
				result += Integer.toString((aB & 0xff) + 0x100, 16).substring(1);// 加0x100是因为有的b[i]的十六进制只有1位
			}
			return result;
		}catch (Exception e){
			e.printStackTrace();
		}
		return "";
	}
}